package servlet;

import jdbc.StudentHomeworkJdbc;
import model.Homework;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if("get".equalsIgnoreCase(req.getMethod())){
            // get请求
            req.getRequestDispatcher("login.jsp").forward(req, resp);

        }else {
            //post请求
            String account = (String)req.getParameter("account");
            String password = (String)req.getParameter("password");
            System.out.println("login servlet:  " + account + "    "+ password);
            if(account.equals("1111") && password.equals("1111")){   //老师登录
                System.out.println("教师登录成功:  " + account + "  " + password);
                Cookie cookie = new Cookie("account", account);
                resp.addCookie(cookie);
                resp.sendRedirect("ts");
            }
            else if(!account.equals("1111")){
                String result = StudentHomeworkJdbc.getPassword(account);
                if(password.equals(result)){    //学生登录成功
                    System.out.println("登录成功:  "+ account+"   "+password );
                    List<Homework> list = StudentHomeworkJdbc.get_student_homework(account);
                    Cookie acc = new Cookie("account",account);
                    resp.addCookie(acc);
                    resp.sendRedirect("sh");
                }
                else {
                    System.out.println("学生登录失败");
                    req.getRequestDispatcher("login.jsp").forward(req, resp);
                }
            }
            else {
                System.out.println("教师登录失败");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
